package com.hzit.listener;

import com.hzit.entity.Student;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import java.util.ArrayList;
import java.util.List;

/**
 * 监听application及其属性值的变化
 * ServletContextListener: 监听application(servletContext)的生命周期的值的变化。
 * ServletContextAttributeListener：监听application的属性值的变化
 */
@WebListener
public class MyApplicationListener implements ServletContextListener, ServletContextAttributeListener {
	// 1. application初始化时
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//1.1 获取到application对象
		ServletContext servletContext = sce.getServletContext();
		//1.2 构造学生对象，并放入集合中
		Student st1 = Student.builder().sid(1001).sname("张三").sex("男").age(20).addr("上海").cid(1).build();
		Student st2 = Student.builder().sid(1002).sname("李四").sex("男").age(22).addr("西湖").cid(2).build();
		Student st3 = new Student(1003,"王五","男",22,"杭州",1);
		List<Student> studentList = new ArrayList<>();
		studentList.add(st1);
		studentList.add(st2);
		studentList.add(st3);
		//1.3 将学生集合放到application作用域中
		servletContext.setAttribute("students",studentList);

		System.out.println("MyApplicationListener---> contextInitialized()");
	}
	// 2. application销毁时
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("MyApplicationListener---> contextDestroyed()");
	}
	//3. 在application作用域中添加属性
	@Override
	public void attributeAdded(ServletContextAttributeEvent event) {
		System.out.println("MyApplicationListener---> attributeAdded()");
	}
	//4. 在application作用域中移除属性
	@Override
	public void attributeRemoved(ServletContextAttributeEvent event) {
		System.out.println("MyApplicationListener---> attributeRemoved()");
	}

	@Override
	public void attributeReplaced(ServletContextAttributeEvent event) {

	}

}
